package com.bsh.controller.advice;


import com.bsh.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
/**
 * 全局异常处理
 */
public class MyControllerAdvice {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result bingError(MethodArgumentNotValidException e) {
        e.printStackTrace();
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return Result.fail(objectError.getDefaultMessage());
    }


    @ExceptionHandler(Exception.class)
    public Result myError(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.fail(StringUtils.isEmpty(e.getMessage())? "请求异常": e.getMessage());
    }
}






